
<template>
  <div ref="videoPlay" style="width: 100%;height: 100%"></div>
</template>

<script setup lang="ts">
import Player, { Events } from 'xgplayer';
import 'xgplayer/dist/index.min.css';
import LivePreset from 'xgplayer/es/presets/live'
import FlvPlugin from 'xgplayer-flv'

const videoPlay = ref(null)
let frameSkipInterval = null
let player;

const props = defineProps({
  playUrl: String,
})

onMounted(()=>{
  initPlayer()
})

watch(
    () => props.playUrl,
    (newVal, oldVal) => {
      replay()
    }
)

function initPlayer(){
  player = new Player({
    lang: 'zh',
    el: videoPlay.value as HTMLElement,
    url: import.meta.env.VITE_VIDEO_API + props.playUrl,
    height: '100%',
    width: '100%',
    videoFillMode: 'fill',
    playsinline: true,
    plugins: [FlvPlugin],
    presets: [LivePreset],
    controls: {
      autoHide: false,
      mode: 'flex',
    },
    autoplayMuted: true,
    autoplay: true,
    screenShot:true,
    ignores:['start','play','playbackRate','cssfullscreen'],
  })
  player.on(Events.USER_ACTION, (data) => {
    if (!player.isFullscreen && data.action === 'switch_play_pause'){
      // 播放器进入全屏状态
      player.getFullscreen()
    } else {
      player.play()
    }
  })
  player.on(Events.PAUSE, () => {
    player.play()
  })
  // 监听全屏变化
  player.on(Events.FULLSCREEN_CHANGE, (isFullscreen) => {
    if (isFullscreen) {
      // 全屏
      player.play()
    } else {
      // 退出全屏
    }
  })

  player.on(Events.ERROR, (error) => {
    // 出现播放错误
    setTimeout(()=>{
      replay()
    },3000)
  })
  frameSkip()
}

function frameSkip(){
  setInterval(()=> {
    if (player && player.buffered && player.buffered.length) {
      // 获取buffered与currentTime的差值
      let diff = player.buffered.end(0) - player.currentTime;
      // 如果差值大于等于5s 手动跳帧 这里可根据自身需求来定
      if (diff >= 5) {
        //手动跳帧
        player.currentTime = player.buffered.end(0);
      }
    }
  },3 * 1000)
}

function destroy(){
  player.destroy()
  player = null
  frameSkipInterval && clearInterval(frameSkipInterval)
  frameSkipInterval = null
}

function replay(){
  destroy()
  initPlayer()
}

onBeforeUnmount(()=>{
  destroy()
})
</script>


<style scoped lang="scss">

</style>